import URL from 'url'

/**
 * 获取Url参数，
 *
 * @param {any} url //url地址
 * @param {any} params //参数名
 * 有params返回参数名的值，string
 * 没有parama 返回整个参数 object
 * 例子：
 * http://abc.com/xx?id=1
 * getUrlParams('id') ==> 1
 */
export const getUrlParams = (params = '', url = window.location.href) =>
  params
    ? URL.parse(url, { querystring: true }).query[params]
    : URL.parse(url, { querystring: true })

/**
 * @description 获取url参数
 * @param url
 * @return {{}}
 */
export let getUrlParam = url => {
  url = url ? url : window.location.href
  let _pa = url.substring(url.indexOf('?') + 1),
    _arrS = _pa.split('&'),
    _rs = {}
  for (let i = 0, _len = _arrS.length; i < _len; i++) {
    let pos = _arrS[i].indexOf('=')
    if (pos === -1) {
      continue
    }
    let name = _arrS[i].substring(0, pos)
    _rs[name] = window.decodeURIComponent(_arrS[i].substring(pos + 1))
  }
  return _rs
}

/**
 * @description 手机类型判断
 * @param type
 * @return {*}
 */
export let browserInfo = type => {
  switch (type) {
    case 'android':
      return navigator.userAgent.toLowerCase().indexOf('android') !== -1
    case 'iphone':
      return navigator.userAgent.toLowerCase().indexOf('iphone') !== -1
    case 'ipad':
      return navigator.userAgent.toLowerCase().indexOf('ipad') !== -1
    case 'weixin':
      return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
    default:
      return navigator.userAgent.toLowerCase()
  }
}
